package com.csdj.wenjun.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.csdj.wenjun.common.CacheConstant;
import com.csdj.wenjun.entity.User;
import com.csdj.wenjun.mapper.UserMapper;
import com.csdj.wenjun.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csdj.wenjun.utils.EncryptUtil;
import com.csdj.wenjun.utils.RandomUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wenjun
 * @since 2022-01-12
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private RedisService redisService;

    public User login(String username, String password) {
        String dePass = EncryptUtil.getMd5(password);
        if(StringUtils.hasText(dePass)){
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(User::getUsername,username).eq(User::getPassword,dePass);
            User user = getOne(queryWrapper);
            if(user != null){
                setToken(user);
                redisService.setString(CacheConstant.TOKEN_PREFIX+user.getId(),user.getToken(),1800);
                return user;
            }
        }
        return null;
    }


    private void setToken(User user){
        if(user != null){
            user.setToken(RandomUtil.genToken());
        }
    }
}
